<template>
	<view v-if="location">

		<view style="position: fixed;left: 0rpx;right: 0rpx;top: 0rpx;z-index: 100;">
			<view :style="{height: statuBarHeight+'px'}" style="background-color: #2869FE;"></view>
			<!-- 顶部 -->
			<view class="cflex-r" style="height: 44px;justify-content: space-between;align-items: center;background-color: #2869FE;
				padding-right:30rpx;padding-left: 30rpx;">
				<view class="cflex-r" style="align-items: center;">
					<image src="/static/qieTu/dingWei.png" style="width: 40rpx;height: 40rpx"></image>
					<view class="cflex-r" style="align-items: center;width: 260rpx;" @tap="locationClick()">
						<text class="u-font-14 u-m-l-5"
							style="font-weight: bold;color: #333333;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;color: #fff;">{{location.address===''?"请选择服务地址":location.address}}</text>
						<view class="cflex-r" style="align-items: center;margin-left: 5rpx;">
							<image class="u-m-l-5" src="/static/qieTu/xiaLa.png" style="width: 18rpx;height: 12rpx;">
							</image>
						</view>
						<image @click="goXiaoXi()" :style="{'padding-right':device==='WX'?'180rpx':'0rpx'}"
							src="/static/qieTu/lingDang.png" style="width: 48rpx;height: 48rpx;"></image>
						<view v-if="isread==1"
							:style="{'top':device==='WX'?'5rpx':'5rpx','right':device==='WX'?'186rpx':'8rpx'}"
							style="width: 13rpx;height: 13rpx;background-color: red;border-radius: 100%;position: absolute;">
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="position: relative;">
		</view>

		<view :style="{height:statuBarHeight+44+'px'}"></view>

		<!-- 时间 -->
		<view class="cflex-r u-p-10"
			style="justify-content: space-around;align-items: center;background-color: #FFFFFF;">
			<view @click="tabClick(Tindex)" v-for="(item,Tindex) in tabList" :key="Tindex" class="cflex-c"
				style="justify-content: center; align-items: center;">
				<view class="cflex-c" style="justify-content: center;align-items: center;"
					:style="{color:item.isSelect?'#2869FE':'#707070',fontWeight:item.isSelect?'bold':'normal'}">
					<view>{{item.text}}</view>
					<view class="u-m-t-10">{{item.time}}</view>
				</view>
				<view :style="{opacity:item.isSelect?1:0}" class="u-m-t-10"
					style="width: 60rpx;height: 8rpx; background-color: #2869FE;border-radius: 20rpx;"></view>
			</view>
		</view>
		<!-- 订单状态 -->
		<view class="cflex-r u-m-t-20 u-m-b-30 u-p-l-40 u-p-r-35" style="justify-content: space-between;
					 align-items: center;background-color: #FFFFFF;height: 100rpx;">
			<text class="u-font-15" style="font-weight: bold;">接单状态</text>
			<u-switch v-model="checked" active-color="#2869FE" inactive-color="#eee"
				@change="switchClick(timeList)"></u-switch>
		</view>
		<!-- 服务时间 -->
		<view v-show="checked" class="cflex-r container"
			style="justify-content: space-around;align-items: center;margin: 0 20rpx 0 20rpx;color:#fff">
			<!-- 时间 -->
			<view class="cflex-c u-m-b-20 u-font-12" style="justify-content: center;
						 align-items: center;border-radius: 20rpx;width: 150rpx; padding-bottom: 15rpx;padding-top: 15rpx;
					position: relative;" v-for="(item,timeIndex) in timeList" :key="timeIndex"
				:style="{backgroundColor:item.status === 1?'#2869FE':'#DCDCDC'}" @tap="itemClick(item)">
				<text style="font-size: 28rpx;">{{item.startime}}</text>
				<text style="font-size: 28rpx;">至</text>
				<text style="margin-top: 10rpx;font-size: 28rpx;">{{item.endtime}}</text>
				<image v-if="item.status === 0" src="../static/qieTu/hxj.png"
					style="width: 75rpx;height: 55rpx;position: absolute;top: 0;right: 0;"></image>
				<image v-if="item.status === 0" src="../static/peiZhi/p2.png"
					style="width: 45rpx;height: 45rpx;position: absolute;top: 0;right: 5rpx;"></image>

				<image v-if="item.isHaveOrder == 1" src="../static/qieTu/xj.png"
					style="width: 75rpx;height: 55rpx;position: absolute;top: 0;right: 0;"></image>
				<image v-if="item.isHaveOrder == 1" src="../static/peiZhi/p1.png"
					style="width: 45rpx;height: 45rpx;position: absolute;top: 0;right: 5rpx;"></image>
			</view>
		</view>
		<view class="" style="display: flex;align-items: center;">
			<view class="type_box">
				<view class="type"></view>
				<view class="">工作</view>
			</view>
			<view class="type_box">
				<view class="type" style="background-color: #DCDCDC;"></view>
				<view class="">休息</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		auth
	} from '../common/authorize.js'; //权限判断
	export default {
		data() {
			return {
				isread: 0,
				timeList: [],
				tabList: [],
				current: 0,
				checked: true,
				location: {
					lat: null,
					lng: null,
					address: '',
				},
				device: "APP", //表示当前运行的平台
				wId: ''
			}
		},
		onLoad() {

			//#ifdef MP-WEIXIN
			this.device = "WX"
			//#endif
		},
		onShow() {
			this.getDay();
			this.showTime()
			this.getLocation();
			console.log("show");
			let isLogin = this.$store.state.isLogin;
			if (isLogin == true) {
				this.onRequest();
			} else {
				return
			}
		},
		methods: {

			showTime() {
				this.$request("timeXxConfig/time/list").then(res => {
					console.log(res)
					this.timeList = res.rows
					this.timeList.forEach((item, i) => {
						item.status = 1
						item.isHaveOrder = 0
					})

					this.onRequest()
					this.timeWork()
				});
			},
			onRequest() {
				this.$request("timeXxConfig/rest/time/list", {
					wid: this.wId,
					day: this.tabList[this.current].day
				}).then(res => {
					if (res.rows.length > 0) {
						res.rows.forEach((item, i) => {
							this.timeList.forEach((items, k) => {
								if (item.tcid == items.id) {
									console.log(items.startime + '-' + items.endtime, 'status:' +
										item.status)
									items.status = item.status
								}
							})
						})
						this.timeList = JSON.parse(JSON.stringify(this.timeList))
						console.log(this.timeList)
					}
				});
			},
			timeWork() {
				let obj = {
					day: this.tabList[this.current].day
				}
				this.$request("worker/jiedan/getFuWuTime", obj).then(res => {
					if (res.data.haveOrderTime > 0) {
						res.data.haveOrderTime.forEach((item, i) => {
							this.timeList.forEach((items, k) => {
								if (item == items.id) {
									items.isHaveOrder = 1
								} else {
									items.isHaveOrder = 0
								}
							})
						})
					}
				})
			},
			getInfo(lat, lng) {
				this.$request("worker/other/selectWorker", {
					lat: lat,
					lng: lng
				}).then(res => {
					this.wId = res.data.id
					if (res.data.status == 0) {
						this.checked = false
					} else {
						this.checked = true
					}

				})
			},
			// item点击
			async itemClick(i) {
				if (i.isHaveOrder == 1) {
					uni.showToast({
						title: '该时间有订单，无法更换状态',
						icon: 'none'
					})
					return
				}
				let that = this
				let status = 0
				if (i.status == 1) {
					status = 0
				} else {
					status = 1
				}
				let obj = {
					day: this.tabList[this.current].day,
					tcid: i.id,
					wid: this.wId,
					status: status
				}
				let res = await this.$request("timeXxConfig/add", obj)
				setTimeout(() => {
					that.showTime()
				}, 1000)
			},
			xiuXiTime(star, end) {
				var tempTime = this.timeList;
				var tempList = []
				for (var i = 0; i < tempTime.length; i++) {
					var thisTime = tempTime[i]
					var starTime = Number(thisTime.text1.split(":")[0])
					thisTime.statu = 0
					thisTime.isHaveOrder = 0
					thisTime.isCanClick = false
					if (star <= starTime && starTime < end || end == 0) {
						thisTime.statu = 1
						thisTime.isCanClick = true
					}
					tempList.push(thisTime)
				}
				this.timeList = tempList;
			},
			isHaveOrder(haveOrderTime) {
				var modelTime = this.timeList;
				var tempList = []
				for (var i = 0; i < haveOrderTime.length; i++) {
					var temp = haveOrderTime[i]
					var yuYueTime = Number(temp.yuYueTime.split(" ")[1].split(":")[0])
					var timeSpan = Number(Number(temp.timeSpan) / 60)
					for (var j = 0; j < modelTime.length; j++) {
						var model = modelTime[j]
						var jStar = Number(model.text1.split(":")[0])
						if (yuYueTime <= jStar && jStar <= (yuYueTime + timeSpan)) {
							model.isHaveOrder = 1
						}

						tempList.push(model)
					}
				}
				// this.timeList = tempList;
			},
			noJieDanTime(noJieDanTime) {
				var modelTime = this.timeList;
				var modelList = []
				for (var j = 0; j < modelTime.length; j++) {
					var model = modelTime[j]
					var jStar = Number(model.text1.split(":")[0])
					for (var i = 0; i < noJieDanTime.length; i++) {
						var temp = noJieDanTime[i]
						var star = Number(temp.startime.split(":")[0])
						if (star == jStar) {
							model.statu = 0
							model.isHaveOrder = 0
						}
					}
					modelList.push(model)
				}
				this.timeList = modelList
			},
			// async onRequest() {
			// 	let obj = {
			// 		day: this.tabList[this.current].day
			// 	}
			// 	this.$request("worker/jiedan/getFuWuTime", obj).then(res => {
			// 		console.log("ALL数据====>", res);
			// 		this.isread = res.data.isRead;
			// 		this.checked = res.data.isJieDan == 1 ? true : false

			// 		var star = res.data.starTime.split(":")[0]
			// 		var end = res.data.endTime.split(":")[0]

			// 		star = Number(star)
			// 		end = Number(end)

			// 		var list = []
			// 		for (var i = 0; i < 24; i++) {
			// 			var temp = {}

			// 			if (i <= 9) {
			// 				temp.text1 = "0" + i + ":00"
			// 				temp.text2 = (i + 1) > 10 ? i + ":00" : "0" + (i + 1) + ":00"
			// 				if (i == 9) {
			// 					temp.text2 = "10:00"
			// 				}
			// 			} else {
			// 				temp.text1 = i + ":00"
			// 				temp.text2 = (i + 1) == 24 ? "00:00" : (i + 1) + ":00"
			// 			}
			// 			list.push(temp)
			// 		}
			// 		this.timeList = list

			// 		this.xiuXiTime(star, end)
			// 		if (res.data.haveOrderTime.length > 0) {
			// 			this.isHaveOrder(res.data.haveOrderTime)
			// 		}
			// 		if (res.data.noJieDanTime.length > 0) {
			// 			this.noJieDanTime(res.data.noJieDanTime)
			// 		}


			// 	});
			// },

			// 更改当日接单状态
			switchClick(timeList) {
				var isHaveOrder = false;
				timeList.forEach((item, index) => {
					if (item.isHaveOrder == 1) {
						isHaveOrder = true
						// return;
					}
				})
				if (isHaveOrder) {
					uni.showToast({
						title: "当前有订单，无法修改状态",
						icon: 'none'
					})
					this.checked = true
					return
				} else {
					this.$request("worker/jiedan/changeFuWu", {
						day: this.tabList[this.current].day
					}).then(res => {
						console.log(res, 2222)
						if (res.code == 500) {
							uni.showToast({
								title: "当前有订单，无法修改状态",
								icon: 'none'
							})
							this.checked = true
							return
						}
						this.onRequest();
					});
				}

			},
			// 获取日期
			getDay() {
				var tabList = [];
				for (var i = 0; i < 6; i++) {
					//获取日期
					var today = new Date();
					var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * i;
					today.setTime(targetday_milliseconds); //注意，这行是关键代码
					var tYear = today.getFullYear();
					var tMonth = today.getMonth();
					var tDate = today.getDate();
					tMonth = this.doHandleMonth(tMonth + 1);
					tDate = this.doHandleMonth(tDate);

					var tab = {}
					tab.isSelect = false
					if (i == 0) {
						tab.text = "今天"
						tab.isSelect = true
					} else if (i == 1) {
						tab.text = "明天"
					} else {
						var text = "周" + "日一二三四五六".charAt(today.getDay());
						tab.text = text;
					}
					tab.time = tMonth + "-" + tDate
					tab.day = tYear + "-" + tMonth + "-" + tDate
					tabList.push(tab);
				}
				this.tabList = tabList;
				//console.log("tabList===========>",this.tabList);
			},
			doHandleMonth(month) {
				var m = month;
				if (month.toString().length == 1) {
					m = "0" + month;
				}
				return m;
			},
			goXiaoXi() {
				uni.navigateTo({
					url: '../pagesB/my/xitongxiaoxi'
				})
			},
			tabClick(Tindex) {
				this.tabList[this.current].isSelect = false;
				this.tabList[Tindex].isSelect = true;
				this.current = Tindex;
				this.showTime()

			},
			getCity(address) {
				let city = address.match(/.*(自治区|区|县|自治县)/g);
				if (city !== null) { //不为空，也就是地址中区、县
					city = city[0]; //取第一个匹配对象
					if (/区/.test(city) && !(/[县]/.test(city))) { //匹配只有区没有县的
						if (/区.*区/.test(city)) { //出现两次区如：黔江区XX小区
							city = address.slice(address.indexOf("市") + 1, address.indexOf("区") + 1)
						} else { //只有一个区如渝北区XX街道
							city = address.match(/.*[(区)|(自治区)]/g)[0]
							city = city.replace(/^(.*市)/, '')
						}
						// //console.log("if1",city)
					}
					if (!(/[区]/.test(city)) && /县/.test(city)) { //只有县如重庆市垫江县
						city = address.match(/.*[(县)|(自治县)]/g)[0]
						city = city.replace(/^(.*市)/, '')
						// //console.log('if2',city)
					}
					if (/区/.test(city) && /县/.test(city)) { //有区有县如垫江县XX社区
						city = address.match(/.*[(县)|(自治县)]/g)[0]
						city = city.replace(/^(.*市)/, '')
						// //console.log('if3',city)
					}
				} else {
					city = "";
					// //console.log("else",city);
				}
				return city;
			},
			async locationClick() { //选择服务地址
				console.log("选地址"); //微信开发者工具点了可能没有反应
				let res = await auth.authLocation(); //判断是否开启定位
				if (res === false) {
					auth.noLocation();
				}
				if (res) {
					let that = this;
					uni.chooseLocation({
						success: (res) => {
							console.log("选择", res)
							this.location.address = res.name;
							this.location.lat = res.latitude;
							this.location.lng = res.longitude;
							that.$store.commit("setLat", res.latitude)
							that.$store.commit("setLng", res.longitude)
							that.$store.commit("setAddress", res.name);
							let city = that.getCity(res.address);

							// uni.showModal({
							// 	title:'地址',
							// 	content:JSON.stringify(res)
							// })
							if (city === "") //获取不到区县如大学城等轻轨站
							{
								that.$request("common/getAddreseByLocation").then(res => {
									city = that.getCity(res.msg);
								})
							}
							that.$store.commit("setCity", city); //存储起来


						}
					})
				}
			},
			// 获取当前定位，微信小程序会获取不到具体地址(如:XX市XX区)
			async getLocation() {
				let that = this
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					success: function(res) {
						console.log("位置", res)
						// //console.log("位置",res.address.poiName)
						that.$store.commit("setLat", res.latitude)
						that.$store.commit("setLng", res.longitude)


						that.getInfo(res.latitude, res.longitude)
						// uni.showModal({
						// 	title:'weiz',
						// 	content:JSON.stringify(res)
						// })
						// #ifdef APP-PLUS
						if (res.address) {
							that.$store.commit("setAddress", res.address.poiName)
							//console.log("city",res.address)
							that.$store.commit("setCity", res.address.district)
						}
						// #endif

						// #ifdef MP-WEIXIN
						if (that.location.address == '') {
							that.$request("common/getAddreseByLocation").then(res => {
								//console.log("地址==============>",res.msg);
								that.$store.commit("setAddress", res.msg);
								that.location.address = res.msg;
								let city = that.getCity(res.msg)
								//console.log('city',city)
								that.$store.commit("setCity", city);
							})
						}
						// #endif

					},
					fail(res) {
						if (err.errMsg.includes('auth deny')) {
							// 用户拒绝授权，引导至设置页
							uni.showModal({
								title: '权限申请',
								content: '需要位置权限以提供[社工定位]',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting(); // 打开应用设置页
									}
								}
							});
						}
					}
				});
				// this.getIp();
				this.location.address = uni.getStorageSync("address");
				this.location.lat = uni.getStorageSync("lat");
				this.location.lng = uni.getStorageSync("lng");
			}
			// //console.log("是否开启",res)
			// this.location.address = uni.getStorageSync("address");
			//console.log(this.location.address);
		},
		computed: {
			statuBarHeight() {
				// //console.log(this.$store.state.sysInfo.statusBarHeight)
				return this.$store.state.sysInfo.statusBarHeight;
			}
		}
	}
</script>

<style scoped>
	.container {
		border-radius: 20rpx;
		flex-wrap: wrap;
	}

	.type_box {
		display: flex;
		align-items: center;
		margin-left: 60rpx;
	}

	.type {
		width: 35rpx;
		height: 35rpx;
		border-radius: 50%;
		background-color: #2869FE;
		margin-right: 20rpx;
	}
</style>